import base64
import random
import time
import uuid

def xc_base64_encode_strs(key,secret,strs):
    key_len = len(key)
    secret_len = len(secret)
    blank_str = ""
    for i in range(0,key_len):
        blank_str += random.choice(key)
    for i in range(0,secret_len):
        blank_str += random.choice(secret)
    strs.insert(0, blank_str)
    __str_base64s = []
    for __str in strs:
        __str_base64 = base64.b64encode(__str.encode("utf-8")).decode("utf-8")
        __str_base64s.append(__str_base64)
    __result = ",".join(__str_base64s)
    __result_base64 = base64.b64encode(__result.encode("utf-8")).decode("utf-8")
    __result_base64_a =__result_base64[0:key_len]
    __result_base64_b =__result_base64[key_len:]
    __result_base64_b_len = len(__result_base64_b)
    __result_base64_safe = str(__result_base64_b_len)+"_"+blank_str+__result_base64_b+__result_base64_a
    return __result_base64_safe

def xc_base64_decode_result(key,secret,result_base64_safe):
    key_len = len(key)
    secret_len = len(secret)
    blank_str_len = key_len + secret_len
    ret = False
    msg = "unknown error"
    strs = []
    try:
        __result_base64_b_len_str = result_base64_safe.split("_")[0]
        __result_base64_b_len = int(__result_base64_b_len_str)
        __prefix = len(__result_base64_b_len_str) + 1 + blank_str_len

        __result_base64_temp = result_base64_safe[__prefix:]
        __result_base64_b = __result_base64_temp[0:__result_base64_b_len]
        __result_base64_a = __result_base64_temp[__result_base64_b_len:]
        __result_base64 = __result_base64_a + __result_base64_b # 恢复成未加密状态下的base64字符串

        __result = base64.b64decode(__result_base64).decode("utf-8")

        __str_base64s = __result.split(",")

        for __str_base64 in __str_base64s:
            __str = base64.b64decode(__str_base64).decode("utf-8")
            strs.append(__str)

        if len(strs) > 0:
            strs.pop(0) # 把加密时存放的blank_str去除掉
            msg = "success"
            ret = True
        else:
            msg = "empty"

    except Exception as e:
        # msg = str(e)
        msg = "illegal request"

    return ret,msg,strs
def xc_get_timestamp():
    # 获取秒级时间戳
    return int(time.time())

def xc_gen_random_code(prefix="rand"):
    """
    产生永远不重复的random_code
    :param prefix: 编码前缀
    :return:
    """
    d= time.strftime("%Y%m%d%H%M%S")
    # d = time.strftime("%Y%m%d")
    val = str(uuid.uuid5(uuid.uuid1(), str(uuid.uuid1())))
    a = val.split("-")[0]
    random_code = "%s%s%s%d" % (prefix, d, a, random.randint(100000, 999999))
    return random_code